package com.woniu.util;

import java.io.IOException;
import java.io.InputStream;

public class FileUtil {

    public static boolean isPdf(byte[] header) {
        return header[0] == 0x25 && header[1] == 0x50 && header[2] == 0x44 && header[3] == 0x46;
    }

    public static boolean isGif(byte[] header) {
        return header[0] == 'G' && header[1] == 'I' && header[2] == 'F' && header[3] == '8';
    }

    public static boolean isPng(byte[] header) {
        return header[0] == (byte) 0x89 && header[1] == (byte) 0x50 && header[2] == (byte) 0x4E
                && header[3] == (byte) 0x47;
    }

    public static boolean isJpg(byte[] header) {
        return header[0] == (byte) 0xFF && header[1] == (byte) 0xD8;
    }


    public static boolean isImageFile(InputStream fis) {
        try {
            byte[] bytes = new byte[8];
            fis.read(bytes);
            // JPEG
            String jpegMagicNumber = "FFD8FF";
            // PNG
            String pngMagicNumber = "89504E47";
            // GIF
            String gifMagicNumber = "474946";
            // BMP
            String bmpMagicNumber = "424D";
            // WEBP
            String webpMagicNumber = "52494646";

            String fileMagicNumber = bytesToHex(bytes).toUpperCase();

            return fileMagicNumber.startsWith(jpegMagicNumber) ||
                    fileMagicNumber.startsWith(pngMagicNumber) ||
                    fileMagicNumber.startsWith(gifMagicNumber) ||
                    fileMagicNumber.startsWith(bmpMagicNumber) ||
                    fileMagicNumber.contains(webpMagicNumber);
        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
            return false;
        }
    }
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}
